<template>
  <div class="page-wrapper">
    <div class="app-container">
      <!-- 页面头部 -->
      <PageHeader back-text="返回项目列表" back-type="back" :title="projectInfo.proName || '加载中...'" />

      <!-- 项目详情卡片 -->
      <ProjectDetail :project-info="projectInfo" :loading="projectLoading" />

      <!-- 项目计划卡片 -->
      <el-card class="mb-6 box-card" v-loading="loading">
        <!-- 搜索栏 -->
        <div class="search-section mb-4">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" class="search-form">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 300px"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
            <!-- 项目计划状态显示 -->
            <el-form-item style="margin-left: auto">
              <ProjectStatusDisplay label="当前项目计划状态" :status-options="approval_commit_status" :status-value="projectInfo.flowStatus" />
            </el-form-item>
          </el-form>
        </div>

        <!-- 项目计划操作按钮 -->
        <div class="card-header mb-4">
          <div class="card-header-left">
            <span class="title">绩效计划</span>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="Check"
                  :disabled="!hasEditingData || !checkContractStatus(projectInfo.proStatus)"
                  @click="handleBatchSave"
                  v-hasPermi="['project:flow:add']"
                  >保存</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="Delete"
                  :disabled="!hasEditingData || !checkContractStatus(projectInfo.proStatus)"
                  @click="handleBatchDelete"
                  v-hasPermi="['project:flow:remove']"
                  >删除</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-dropdown @command="handleMoreCommand" v-hasPermi="['project:flow:import', 'project:flow:export']">
                  <el-button type="warning" plain size="default" :disabled="!checkContractStatus(projectInfo.proStatus)">
                    导入导出
                    <el-icon class="el-icon--right">
                      <ArrowDown />
                    </el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="download-template">
                        <el-icon style="vertical-align: middle">
                          <Download />
                        </el-icon>
                        <span style="margin-left: 4px">下载模板</span>
                      </el-dropdown-item>
                      <el-dropdown-item command="import-data" :disabled="!canImport()">
                        <el-icon style="vertical-align: middle">
                          <Upload />
                        </el-icon>
                        <span style="margin-left: 4px">导入数据</span>
                      </el-dropdown-item>
                      <el-dropdown-item command="export-data">
                        <el-icon style="vertical-align: middle">
                          <Download />
                        </el-icon>
                        <span style="margin-left: 4px">导出数据</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="Plus"
                  @click="handleAdd"
                  :disabled="!checkContractStatus(projectInfo.proStatus)"
                  v-hasPermi="['project:flow:add']"
                  >添加流程</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <div style="display: flex; align-items: center; gap: 8px">
                  <el-select v-model="sortField" placeholder="请选择排序字段" style="width: 170px" clearable @change="handleSortChange">
                    <el-option label="总绩效" value="totalPerf" />
                    <el-option label="创建时间" value="createTime" />
                  </el-select>
                  <el-button
                    v-if="sortField"
                    :icon="sortOrder === 'asc' ? 'ArrowUp' : 'ArrowDown'"
                    @click="toggleSortOrder"
                    type="info"
                    plain
                    size="small"
                    :title="sortOrder === 'asc' ? '当前为正序，点击切换为逆序' : '当前为逆序，点击切换为正序'"
                  >
                    {{ sortOrder === 'asc' ? '正序' : '逆序' }}
                  </el-button>
                </div>
              </el-col>
            </el-row>
          </div>
          <div class="flex items-center" style="gap: 6px">
            <RefreshButton @refresh="handleQuery" :has-permi="['project:flow:list']" />
            <el-button
              type="primary"
              :disabled="!checkContractStatus(projectInfo.proStatus)"
              size="large"
              @click="handleSubmit"
              :loading="submitLoading"
              v-hasPermi="['project:flow:audit']"
            >
              <el-icon>
                <Upload />
              </el-icon>
              提交项目计划
            </el-button>
          </div>
        </div>

        <el-form ref="formRef" :model="form">
          <div class="flow-container">
            <div class="scroll-tip-container">
              <div class="scroll-tip">
                <el-icon class="tip-icon">
                  <ArrowLeft />
                </el-icon>
                <span class="tip-text">左右滑动查看更多信息</span>
                <el-icon class="tip-icon">
                  <ArrowRight />
                </el-icon>
              </div>
            </div>
            <el-table :data="flowList" border style="width: 100%" row-key="id" :row-class-name="tableRowClassName">
              <!-- 技术流程（展示） -->
              <el-table-column width="200" label="技术流程" align="center" fixed="left">
                <template #default="scope">
                  <span>{{ scope.row.techFlow || '-' }}</span>
                </template>
              </el-table-column>

              <!-- 工作内容 -->
              <el-table-column width="300" label="工作内容" align="left" fixed="left">
                <template #default="scope">
                  <el-input
                    v-if="scope.row.isEditing"
                    v-model="scope.row.workContent"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入工作内容（可选）"
                  />
                  <el-tooltip v-else :content="scope.row.workContent" placement="top" :disabled="!scope.row.workContent">
                    <span class="text-overflow">{{ scope.row.workContent }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <!-- 计划分项工作内容占比 -->
              <el-table-column width="200" label="计划分项工作内容占比（%）" align="center">
                <template #default="scope">
                  <PercentageInput
                    v-if="scope.row.isEditing"
                    v-model="scope.row.planRatio"
                    placeholder="请输入占比（0-100，保留两位小数）"
                    :required="true"
                    @change="triggerCalculation(scope.row)"
                  />
                  <span v-else>
                    <span v-if="scope.row.planRatio">{{ formatPercentage(scope.row.planRatio) }}</span>
                    <span v-else>-</span>
                  </span>
                </template>
              </el-table-column>

              <!-- 人员 -->
              <el-table-column width="200" label="人员（人）" align="center">
                <template #default="scope">
                  <PersonInput
                    v-if="scope.row.isEditing"
                    v-model="scope.row.persons"
                    placeholder="请输入人数（大于0的整数）"
                    :required="true"
                    @change="triggerCalculation(scope.row)"
                  />
                  <span v-else>
                    <span v-if="scope.row.persons">{{ scope.row.persons }}人</span>
                    <span v-else>-</span>
                  </span>
                </template>
              </el-table-column>

              <!-- 工天 -->
              <el-table-column width="200" label="工天（天）" align="center">
                <template #default="scope">
                  <DayInput
                    v-if="scope.row.isEditing"
                    v-model="scope.row.workDays"
                    placeholder="请输入工天（大于0，保留两位小数）"
                    :required="true"
                    @change="triggerCalculation(scope.row)"
                  />
                  <span v-else>
                    <span v-if="scope.row.workDays">{{ scope.row.workDays }}天</span>
                    <span v-else>-</span>
                  </span>
                </template>
              </el-table-column>

              <!-- 计划总人工天 -->
              <el-table-column width="200" label="计划总人工天（天）" align="center">
                <template #default="scope">
                  <span class="calculated-value">{{ Number(scope.row.totalPd) || 0 }}天</span>
                </template>
              </el-table-column>

              <!-- 单位绩效 -->
              <el-table-column width="200" label="单位绩效（元/人/天）" align="center">
                <template #default="scope">
                  <MoneyInput
                    v-if="scope.row.isEditing"
                    v-model="scope.row.unitPerf"
                    placeholder="请输入单位绩效（保留两位小数）"
                    :required="true"
                    :min="0"
                    @change="triggerCalculation(scope.row)"
                  />
                  <span v-else>
                    <span v-if="hasPerDataQueryPermission && scope.row.unitPerf">{{ formatAmount(scope.row.unitPerf) }}元</span>
                    <span v-else>-</span>
                  </span>
                </template>
              </el-table-column>

              <!-- 计划分项工作内容绩效 -->
              <el-table-column width="200" label="该项工作内容绩效绩效（元）" align="center">
                <template #default="scope">
                  <span v-if="hasPerDataQueryPermission" class="calculated-value">{{ formatAmount(scope.row.planPerf) || 0 }}元</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>

              <!-- 差旅 -->
              <el-table-column width="200" label="差旅（元）" align="center">
                <template #default="scope">
                  <MoneyInput
                    v-if="scope.row.isEditing"
                    v-model="scope.row.difference"
                    placeholder="请输入差旅费（保留两位小数）"
                    :min="0"
                    @change="calculateTotalPerf(scope.row)"
                  />
                  <span v-else>
                    <span v-if="hasPerDataQueryPermission && scope.row.difference">{{ formatAmount(scope.row.difference) }}元</span>
                    <span v-else>-</span>
                  </span>
                </template>
              </el-table-column>

              <!-- 办公费 -->
              <el-table-column width="200" label="办公费（元）" align="center">
                <template #default="scope">
                  <MoneyInput
                    v-if="scope.row.isEditing"
                    v-model="scope.row.officeFee"
                    placeholder="请输入办公费（保留两位小数）"
                    :min="0"
                    @change="calculateTotalPerf(scope.row)"
                  />
                  <span v-else>
                    <span v-if="hasPerDataQueryPermission && scope.row.officeFee">{{ formatAmount(scope.row.officeFee) }}元</span>
                    <span v-else>-</span>
                  </span>
                </template>
              </el-table-column>

              <!-- A1费用 -->
              <el-table-column width="200" label="A1费用（元）" align="center">
                <template #default="scope">
                  <MoneyInput
                    v-if="scope.row.isEditing"
                    v-model="scope.row.a1Fee"
                    placeholder="请输入A1费用（保留两位小数）"
                    :min="0"
                    @change="calculateTotalPerf(scope.row)"
                  />
                  <span v-else>
                    <span v-if="hasPerDataQueryPermission && scope.row.a1Fee">{{ formatAmount(scope.row.a1Fee) }}元</span>
                    <span v-else>-</span>
                  </span>
                </template>
              </el-table-column>

              <!-- A2费用 -->
              <el-table-column width="200" label="A2费用（元）" align="center">
                <template #default="scope">
                  <MoneyInput
                    v-if="scope.row.isEditing"
                    v-model="scope.row.a2Fee"
                    placeholder="请输入A2费用（保留两位小数）"
                    :min="0"
                    @change="calculateTotalPerf(scope.row)"
                  />
                  <span v-else>
                    <span v-if="hasPerDataQueryPermission && scope.row.a2Fee">{{ formatAmount(scope.row.a2Fee) }}元</span>
                    <span v-else>-</span>
                  </span>
                </template>
              </el-table-column>

              <!-- 总绩效 -->
              <el-table-column width="200" label="总绩效（含成本）" align="center">
                <template #default="scope">
                  <span v-if="hasPerDataQueryPermission" class="calculated-value">{{ formatAmount(scope.row.totalPerf) || 0 }}元</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>

              <!-- 成本说明 -->
              <el-table-column width="300" label="成本说明" align="left">
                <template #default="scope">
                  <el-input v-if="scope.row.isEditing" v-model="scope.row.costDescription" type="textarea" :rows="3" placeholder="请输入成本说明" />
                  <el-tooltip v-else :content="scope.row.costDescription" placement="top" :disabled="!scope.row.costDescription">
                    <span class="text-overflow">{{ scope.row.costDescription }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <!-- 备注 -->
              <el-table-column width="300" label="备注" align="left">
                <template #default="scope">
                  <el-input v-if="scope.row.isEditing" :rows="3" v-model="scope.row.remark" type="textarea" placeholder="请输入备注" />
                  <el-tooltip v-else :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
                    <span class="text-overflow">{{ scope.row.remark }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <!-- 创建人 -->
              <el-table-column label="创建人" align="center" prop="createBy" width="150" />

              <!-- 创建时间 -->
              <el-table-column label="创建时间" width="150" align="center">
                <template #default="scope">
                  <span>{{ scope.row.createTime ? scope.row.createTime : '-' }}</span>
                </template>
              </el-table-column>

              <!-- 状态 -->
              <el-table-column label="保存状态" width="150" fixed="right" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.id ? 'success' : 'warning'">
                    {{ scope.row.id ? '已保存' : '未保存' }}
                  </el-tag>
                </template>
              </el-table-column>

              <!-- 操作 -->
              <el-table-column label="操作" width="150" fixed="right" align="center">
                <template #default="scope">
                  <!-- 编辑模式下的操作按钮 -->
                  <template v-if="scope.row.isEditing">
                    <el-button size="small" type="danger" @click="cancelEdit(scope.row)"> 取消 </el-button>
                  </template>
                  <!-- 查看模式下的操作按钮 -->
                  <template v-else>
                    <el-tooltip content="修改" placement="top">
                      <el-button
                        link
                        type="primary"
                        :disabled="!checkContractStatus(projectInfo.proStatus)"
                        icon="Edit"
                        @click="editFlow(scope.row)"
                        v-hasPermi="['project:flow:edit']"
                      ></el-button>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                      <el-button
                        link
                        type="danger"
                        :disabled="!checkContractStatus(projectInfo.proStatus)"
                        icon="Delete"
                        @click="deleteFlow(scope.row)"
                        v-hasPermi="['project:flow:remove']"
                      ></el-button>
                    </el-tooltip>
                  </template>
                </template>
              </el-table-column>

              <template #empty>
                <el-empty description="暂无流程数据">
                  <el-button type="primary" @click="handleAdd" :disabled="!checkContractStatus(projectInfo.proStatus)" icon="Plus"
                    >添加流程</el-button
                  >
                </el-empty>
              </template>
            </el-table>
          </div>
        </el-form>
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?proId=' + route.params.proId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="handleImportTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加审核流程相关组件 -->
    <ApprovalFlow
      v-model:visible="approvalFlowVisible"
      :business-type="'PROJECT-SPLIT-FLOW'"
      :business-id="Number(route.params.proId)"
      title="配置项目计划审核流程"
      @confirm="handleApprovalFlowConfirm"
      @cancel="handleApprovalFlowCancel"
      @template-imported="handleTemplateImported"
    />
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { getProInfo } from '@/api/project/init/proInfo';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';
import { globalHeaders } from '@/utils/request';
import { listProFlow, batchSaveProFlow, delProFlow, importData } from '@/api/project/plan/flow';
import type { ProFlowQuery } from '@/api/project/plan/flow/types';
import ApprovalFlow from '@/components/ApprovalFlow/index.vue';
import ProjectDetail from '@/views/project/components/ProjectDetail.vue';
import ProjectStatusDisplay from '@/views/project/components/ProjectStatusDisplay.vue';
import RefreshButton from '@/views/project/components/RefreshButton.vue';
import PageHeader from '@/views/project/components/PageHeader/index.vue';
import { canImport as canImportData } from '@/utils/projectStatusUtils';
import { PercentageInput, MoneyInput, PersonInput, DayInput, formatAmount, formatPercentage } from '@/components/NumberInput';
import { checkContractStatus, checkPermi } from '@/utils/permission';

const route = useRoute();
const router = useRouter();

// 项目信息
const projectInfo = ref<Partial<ProInfoVO>>({});
const projectLoading = ref(false);

// 表单数据
const form = reactive({
  proId: Number(route.params.proId)
});

// 修改 getCurrentInstance 的类型断言
const { proxy } = getCurrentInstance() as any;

// 流程列表（统一管理，包含保存和未保存的）
const flowList = ref<any[]>([]);

// 分页参数
const queryParams = ref<ProFlowQuery>({
  pageNum: 1,
  pageSize: 100,
  proId: Number(route.params.proId),
  params: {}
});

// 总条数
const total = ref(0);

// 加载状态
const loading = ref(false);

// 日期范围
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

// 添加提交按钮相关变量
const submitLoading = ref(false);

// 添加审核流程相关变量
const approvalFlowVisible = ref(false);

// 排序字段
const sortField = ref('');
// 排序顺序
const sortOrder = ref('asc');

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getFlowListData();
};

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryParams.value = {
    pageNum: 1,
    pageSize: 100,
    proId: Number(route.params.proId),
    params: {}
  };
  handleQuery();
};

/**
 * 获取流程列表数据
 * 包含日期范围的处理
 */
const getFlowListData = async () => {
  try {
    loading.value = true;
    const params = { ...queryParams.value };
    // 使用addDateRange工具方法处理创建时间范围
    proxy?.addDateRange(params, dateRange.value, 'CreateTime');
    // 处理排序参数
    if (sortField.value && sortOrder.value) {
      (params as any).orderByColumn = sortField.value;
      (params as any).isAsc = sortOrder.value;
    }
    const res = await listProFlow(params);
    // 将获取的数据设置为流程列表，添加编辑状态标记
    flowList.value = res.rows.map((item) => ({
      ...item,
      isEditing: false,
      originalData: null,
      watchersSet: false
    }));
    total.value = res.total;

    // 为每个流程项设置监听并触发初始计算
    flowList.value.forEach((item) => {
      watchFields(item);
      // 触发初始计算
      triggerCalculation(item);
    });
  } catch (error) {
    console.error('获取流程列表失败:', error);
    ElMessage.error('获取流程列表失败');
  } finally {
    loading.value = false;
  }
};

/**
 * 检查是否可以导入
 */
const canImport = () => canImportData(projectInfo.value.flowStatus);

/**
 * 获取项目信息
 * 根据路由参数中的项目ID获取详细信息
 */
const getProjectDetail = async () => {
  const proId = route.params.proId as string;
  if (!proId) {
    ElMessage.error('项目ID不能为空');
    return;
  }

  try {
    projectLoading.value = true;
    const res = await getProInfo(proId);
    projectInfo.value = res.data || {};
  } catch (error) {
    console.error('获取项目信息失败:', error);
    ElMessage.error('获取项目信息失败');
  } finally {
    projectLoading.value = false;
  }
};

/**
 * 计算总人工天
 */
const calculateTotalPd = (row: any) => {
  row.totalPd = (Number(row.persons) || 0) * (Number(row.workDays) || 0);
  calculatePlanPerf(row);
};

/**
 * 计算计划分项工作内容绩效
 */
const calculatePlanPerf = (row: any) => {
  row.planPerf = (Number(row.unitPerf) || 0) * (Number(row.totalPd) || 0);
  calculateTotalPerf(row);
};

/**
 * 计算总绩效
 */
const calculateTotalPerf = (row: any) => {
  const planPerf = Number(row.planPerf) || 0;
  const difference = Number(row.difference) || 0;
  const officeFee = Number(row.officeFee) || 0;
  const a1Fee = Number(row.a1Fee) || 0;
  const a2Fee = Number(row.a2Fee) || 0;
  row.totalPerf = Number((planPerf + difference + officeFee + a1Fee + a2Fee).toFixed(2));
};

/**
 * 监听相关字段变化
 */
const watchFields = (row: any) => {
  if (row.watchersSet) return;

  // 由于现在使用input事件处理，不需要监听这些字段的变化
  // 计算会在input处理函数中直接调用

  row.watchersSet = true;
};

/**
 * 手动触发行的所有计算
 */
const triggerCalculation = (row: any) => calculateTotalPd(row);

/**
 * 添加流程
 * 创建新的流程行并添加到流程列表中
 */
const handleAdd = () => {
  const newFlow: any = {
    id: undefined,
    proId: Number(route.params.proId),
    flowName: '',
    workContent: '',
    planRatio: null,
    persons: null,
    workDays: null,
    totalPd: 0,
    unitPerf: null,
    planPerf: 0,
    difference: null,
    officeFee: null,
    a1Fee: null,
    a2Fee: null,
    totalPerf: 0,
    costDescription: '',
    remark: '',
    isEditing: true,
    originalData: null,
    watchersSet: false
  };
  flowList.value.push(newFlow);
  watchFields(newFlow);
};

/**
 * 编辑流程
 * 将流程设置为编辑状态
 * @param row 流程行数据
 */
const editFlow = async (row: any) => {
  try {
    // 保存原始数据用于取消时恢复
    row.originalData = JSON.parse(JSON.stringify(row));
    row.isEditing = true;

    // 确保监听器设置标记存在
    if (row.watchersSet === undefined) {
      row.watchersSet = false;
    }

    // 设置字段监听
    watchFields(row);
  } catch (error) {
    console.error('编辑流程失败:', error);
    ElMessage.error('编辑流程失败');
  }
};

/**
 * 校验单行数据
 * @param row 流程行数据
 * @returns 校验结果
 */
const validateFlowRow = (row: any): { valid: boolean; errors: string[] } => {
  const errors: string[] = [];

  // 必填字段校验
  if (!row.flowName || row.flowName.trim() === '') {
    errors.push('工作流程不能为空');
  }

  if (row.planRatio === undefined || row.planRatio === null || row.planRatio === '') {
    errors.push('计划分项内容占比不能为空');
  } else if (row.planRatio < 0 || row.planRatio > 100) {
    errors.push('占比范围为0-100');
  }

  if (row.persons === undefined || row.persons === null || row.persons === '') {
    errors.push('人员不能为空');
  } else if (row.persons < 1) {
    errors.push('人员必须大于0');
  }

  if (row.workDays === undefined || row.workDays === null || row.workDays === '') {
    errors.push('工天不能为空');
  } else if (row.workDays <= 0) {
    errors.push('工天必须大于0');
  }

  if (row.totalPd === undefined || row.totalPd === null || row.totalPd === '') {
    errors.push('计划总人工天不能为空');
  } else if (row.totalPd <= 0) {
    errors.push('计划总人工天必须大于0');
  }

  // 只有在有权限时才校验与钱相关的字段
  if (hasPerDataQueryPermission.value) {
    if (row.unitPerf === undefined || row.unitPerf === null || row.unitPerf === '') {
      errors.push('单位绩效不能为空');
    } else if (row.unitPerf <= 0) {
      errors.push('单位绩效必须大于0');
    }

    if (row.planPerf === undefined || row.planPerf === null || row.planPerf === '') {
      errors.push('计划分项内容绩效不能为空');
    } else if (row.planPerf <= 0) {
      errors.push('计划分项内容绩效必须大于0');
    }

    if (row.totalPerf === undefined || row.totalPerf === null || row.totalPerf === '') {
      errors.push('总绩效不能为空');
    } else if (row.totalPerf <= 0) {
      errors.push('总绩效必须大于0');
    }
  }

  // 非负数校验
  if (row.difference !== undefined && row.difference !== null && row.difference !== '' && row.difference < 0) {
    errors.push('差旅不能为负');
  }

  if (row.officeFee !== undefined && row.officeFee !== null && row.officeFee !== '' && row.officeFee < 0) {
    errors.push('办公费不能为负');
  }

  if (row.a1Fee !== undefined && row.a1Fee !== null && row.a1Fee !== '' && row.a1Fee < 0) {
    errors.push('A1费用不能为负');
  }

  if (row.a2Fee !== undefined && row.a2Fee !== null && row.a2Fee !== '' && row.a2Fee < 0) {
    errors.push('A2费用不能为负');
  }

  return {
    valid: errors.length === 0,
    errors
  };
};

/**
 * 取消编辑
 * @param row 流程行数据
 */
const cancelEdit = (row: any) => {
  if (row.originalData) {
    // 恢复原始数据，但保留监听器状态
    const watchersSet = row.watchersSet;
    Object.assign(row, row.originalData);
    row.isEditing = false;
    row.originalData = null;
    row.watchersSet = watchersSet;
    // 重新设置监听器
    watchFields(row);
  } else {
    // 新增的行，直接从列表中移除
    const index = flowList.value.findIndex((item) => item === row);
    if (index > -1) {
      flowList.value.splice(index, 1);
    }
  }
};

/**
 * 删除已保存的流程
 * @param row 流程行数据
 */
const deleteFlow = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该流程吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await delProFlow(row.id);
    ElMessage.success('删除成功');
    getFlowListData();
  } catch (error) {
    // 用户取消或删除失败，不做处理
  }
};

// 导入相关
const uploadRef = ref();
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/pro/flow/importData'
});

/**
 * 更多下拉菜单事件处理
 */
const handleMoreCommand = (command: string) => {
  const actions = {
    'download-template': handleImportTemplate,
    'import-data': handleImport,
    'export-data': handleExport
  };
  actions[command]?.();
};

/**
 * 下载导入模板
 */
const handleImportTemplate = () => {
  proxy?.download('pro/flow/importTemplate', {}, `project_flow_template_${new Date().getTime()}.xlsx`);
};

/**
 * 导出数据
 */
const handleExport = () => {
  proxy?.download('pro/flow/export', { ...queryParams.value, proId: Number(route.params.proId) }, `project_flow_${new Date().getTime()}.xlsx`);
};

/**
 * 导入按钮操作
 * 打开导入对话框
 */
const handleImport = () => {
  if (!route.params.proId) {
    ElMessage.error('项目ID不能为空');
    return;
  }
  upload.title = '项目计划导入';
  upload.open = true;
  upload.isUploading = false;

  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
};

/**
 * 文件上传相关处理
 */
const handleFileUploadProgress = () => (upload.isUploading = true);

const handleFileSuccess = (response: any) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.clearFiles();
  // 导出结果弹出
  ElMessageBox.alert(response.msg, '导入结果', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确定',
    type: 'info'
  });
  getFlowListData();
};

const submitFileForm = () => uploadRef.value?.submit();

const { project_type, project_status, approval_commit_status } = toRefs<any>(
  proxy?.useDict('project_type', 'project_status', 'approval_commit_status')
);

/**
 * 处理排序变化
 */
const handleSortChange = () => {
  // 如果选择了排序字段但没有选择排序顺序，则设置默认值
  if (sortField.value && !sortOrder.value) {
    sortOrder.value = 'asc';
  }
  // 刷新流程列表
  getFlowListData();
};

/**
 * 切换排序顺序
 */
const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
  // 刷新流程列表
  getFlowListData();
};

/**
 * 处理分页变化
 */
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  getFlowListData();
};

const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getFlowListData();
};

// 计算是否有编辑状态的数据
const hasEditingData = computed(() => {
  return flowList.value.some((item) => item.isEditing);
});

// 检查是否有绩效数据查询权限
const hasPerDataQueryPermission = computed(() => {
  return checkPermi(['project:perdata:query']);
});

/**
 * 批量删除流程
 */
const handleBatchDelete = async () => {
  if (!hasEditingData.value) {
    ElMessage.warning('没有处于编辑状态的数据可以删除');
    return;
  }

  try {
    await ElMessageBox.confirm('是否确认删除所有编辑状态的数据项？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 分离已保存和未保存的项，只处理编辑状态的行
    const savedIds: (number | string)[] = [];
    const unsavedItems: any[] = [];

    flowList.value.forEach((item) => {
      if (item.isEditing === true) {
        // 确保只处理编辑状态的行
        if (item.id) {
          savedIds.push(item.id);
        } else {
          unsavedItems.push(item);
        }
      }
    });

    if (savedIds.length === 0 && unsavedItems.length === 0) {
      ElMessage.warning('没有处于编辑状态的数据可以删除');
      return;
    }

    // 删除已保存的项
    if (savedIds.length > 0) {
      await delProFlow(savedIds);
    }

    // 删除未保存的项
    unsavedItems.forEach((item) => {
      const index = flowList.value.findIndex((flow) => flow === item);
      if (index > -1) {
        flowList.value.splice(index, 1);
      }
    });

    ElMessage.success('删除成功');

    // 重新获取数据
    if (savedIds.length > 0) {
      getFlowListData();
    }
  } catch (error) {
    // 用户取消或删除失败，不做处理
  }
};

/**
 * 批量保存流程
 */
const handleBatchSave = async () => {
  if (!hasEditingData.value) {
    ElMessage.warning('没有处于编辑状态的数据可以保存');
    return;
  }

  try {
    const selectedRows = flowList.value.filter((item) => item.isEditing === true);

    if (selectedRows.length === 0) {
      ElMessage.warning('没有处于编辑状态的数据可以保存');
      return;
    }

    // 批量校验所有选中的行
    const validationErrors: string[] = [];
    selectedRows.forEach((row, index) => {
      const validation = validateFlowRow(row);
      if (!validation.valid) {
        validationErrors.push(`第${index + 1}行：${validation.errors.join('；')}`);
      }
    });

    if (validationErrors.length > 0) {
      ElMessage.error(`保存失败：\n${validationErrors.join('\n')}`);
      return;
    }

    const submitData = selectedRows.map((row) => {
      const data = { ...row };
      // 将 createBy 和 createTime 设置为 null，避免 BO 继承 BaseEntity 时的转换问题
      data.createBy = null;
      data.createTime = null;
      delete data.isEditing;

      delete data.originalData;
      return data;
    });

    await batchSaveProFlow(submitData);
    ElMessage.success('保存成功');

    // 重新获取数据
    getFlowListData();
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

/**
 * 提交项目计划
 */
const handleSubmit = async () => {
  try {
    // 检查是否有未保存的流程数据
    const editingFlows = flowList.value.filter((item) => item.isEditing);
    if (editingFlows.length > 0) {
      // 校验所有编辑中的数据
      const validationErrors: string[] = [];
      editingFlows.forEach((row, index) => {
        const validation = validateFlowRow(row);
        if (!validation.valid) {
          validationErrors.push(`第${index + 1}行：${validation.errors.join('；')}`);
        }
      });

      if (validationErrors.length > 0) {
        ElMessage.error(`提交失败，请先修正以下错误：\n${validationErrors.join('\n')}`);
        return;
      }

      await ElMessageBox.confirm('检测到有未保存的流程数据，是否先保存所有数据再提交？', '提示', {
        confirmButtonText: '保存并提交',
        cancelButtonText: '取消',
        type: 'warning'
      });

      // 先保存所有编辑中的数据
      const allEditingFlows = editingFlows.map((row) => {
        const submitData = { ...row };
        submitData.createBy = null;
        submitData.createTime = null;
        delete submitData.isEditing;
        delete submitData.originalData;
        return submitData;
      });

      await batchSaveProFlow(allEditingFlows);
      ElMessage.success('数据保存成功');

      // 重新获取数据确保最新状态
      await getFlowListData();
      await getProjectDetail();
    }

    // 检查是否有流程数据
    const savedFlows = flowList.value.filter((item) => item.id);
    if (savedFlows.length === 0) {
      ElMessage.warning('请先添加项目流程再提交');
      return;
    }

    // 校验所有已保存的流程数据
    const validationErrors: string[] = [];
    savedFlows.forEach((row, index) => {
      const validation = validateFlowRow(row);
      if (!validation.valid) {
        validationErrors.push(`第${index + 1}行：${validation.errors.join('；')}`);
      }
    });

    if (validationErrors.length > 0) {
      ElMessage.error(`提交失败，请先修正以下错误：\n${validationErrors.join('\n')}`);
      return;
    }

    // 打开审核流程配置对话框
    approvalFlowVisible.value = true;
  } catch (error) {
    console.error('提交前检查失败:', error);
    ElMessage.error('提交失败，请稍后重试');
  }
};

/**
 * 审核流程相关处理
 */
const handleApprovalFlowConfirm = async (data: any) => {
  try {
    ElMessage.success('项目计划提交成功');
    approvalFlowVisible.value = false;
    // 刷新项目详情和流程列表
    await Promise.all([getProjectDetail(), getFlowListData()]);
  } catch (error) {
    console.error('刷新数据失败:', error);
    ElMessage.error('提交成功，但刷新数据失败，请手动刷新页面');
  }
};

const handleApprovalFlowCancel = () => (approvalFlowVisible.value = false);

const handleTemplateImported = (data: any) => {
  ElMessage.success(`审核模板"${data.templateName}"导入成功`);
};

/**
 * 表格行样式和选择状态
 */
const tableRowClassName = ({ row }: { row: any }) => (row.isEditing ? 'editing-row' : '');

onMounted(() => {
  getProjectDetail();
  getFlowListData();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  background: #fff;
  min-height: 48px;
}

.card-header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-header-left .title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-header-left .el-button {
  transition: all 0.2s ease;
}

.card-header-left .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.right .el-button {
  min-width: 140px;
  height: 40px;
  font-size: 14px;
  font-weight: 600;
}

.right .el-button .el-icon {
  margin-right: 6px;
}

.flow-container {
  position: relative;
  margin-top: 20px;

  .scroll-tip-container {
    position: absolute;
    left: 0;
    bottom: -45px;
    flex-shrink: 0;
  }

  .scroll-tip {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-size: 12px;
    color: #909399;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    padding: 6px 12px;
    border-radius: 4px;
    display: inline-flex;
  }

  .tip-icon {
    font-size: 14px;
    color: #909399;
  }

  .tip-text {
    font-size: 12px;
    color: #909399;
  }

  :deep(.el-table) {
    /* 设置表格内容垂直居中 */
    .el-table__cell {
      vertical-align: middle;
    }

    /* 设置输入框样式 */
    .el-input,
    .el-input-number,
    .el-date-editor {
      width: 100%;
    }

    /* 设置文本域样式 */
    .el-textarea__inner {
      min-height: 60px;
      resize: vertical;
    }

    /* 设置数字输入框样式 */
    .el-input-number {
      .el-input__wrapper {
        padding-left: 8px;
        padding-right: 8px;
      }
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

.percentage-input {
  display: flex;
  align-items: center;
  position: relative;

  .percentage-symbol {
    position: absolute;
    right: 5px;
    color: #606266;
    font-size: 14px;
    pointer-events: none;
  }
}

.search-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #dee2e6;
}

.search-form {
  margin: 0;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 16px;
}

.search-form .el-form-item:last-child {
  margin-right: 0;
}

.text-overflow {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  vertical-align: top;
}

.calculated-value {
  color: var(--el-color-danger);
  font-weight: bold;
}

/* 编辑状态行背景色 */
:deep(.editing-row) {
  background-color: var(--el-color-primary-light-9);
}

:deep(.editing-row td) {
  background-color: var(--el-color-primary-light-9) !important;
}

/* 表格内的小尺寸组件调整 */
.flow-container :deep(.el-input__wrapper) {
  min-height: 28px;
}

.flow-container :deep(.el-select .el-input__wrapper) {
  min-height: 28px;
}

.flow-container :deep(.el-date-editor.el-input) {
  width: 100%;
}

.flow-container :deep(.el-date-editor .el-input__wrapper) {
  min-height: 28px;
}

.flow-container :deep(.el-textarea__inner) {
  min-height: 60px;
  resize: vertical;
}

.flow-container :deep(.el-input-number) {
  width: 100%;
}

.flow-container :deep(.el-input-number .el-input__wrapper) {
  min-height: 28px;
}

/* 表单验证错误样式 */
.flow-container :deep(.is-error .el-input__wrapper),
.flow-container :deep(.is-error .el-date-editor .el-input__wrapper),
.flow-container :deep(.is-error .el-input-number .el-input__wrapper) {
  border-color: var(--el-color-danger) !important;
  box-shadow: 0 0 0 1px var(--el-color-danger) inset !important;
}

.flow-container :deep(.is-error .el-input__inner) {
  border-color: var(--el-color-danger) !important;
}

/* 悬停时的错误状态 */
.flow-container :deep(.is-error .el-input__wrapper:hover),
.flow-container :deep(.is-error .el-date-editor .el-input__wrapper:hover),
.flow-container :deep(.is-error .el-input-number .el-input__wrapper:hover) {
  border-color: var(--el-color-danger) !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 8px;
  }

  /* 项目计划状态响应式 */
  .flow-status-content {
    flex-direction: column;
    gap: 12px;
    padding: 12px 16px;
    text-align: center;
  }

  .flow-status-icon {
    width: 40px;
    height: 40px;
  }

  .flow-status-label {
    font-size: 13px;
  }

  .flow-status-value .el-tag {
    font-size: 13px;
    padding: 6px 12px;
  }

  .flow-status-description {
    margin-left: 0;
    text-align: center;
    max-width: none;
    font-size: 12px;
  }
}

/* 新增的页面包装器样式 */
.page-wrapper {
  width: 100%;
  height: 100%;
}

.box-card {
  border-radius: 12px !important;
}
</style>
